﻿
@{
    ViewBag.Title = "InventoryView";
    Layout = "~/Views/Shared/_MyLayout.cshtml";
}

@section head{
    <script src="~/Scripts/exportJs.js"></script>
    <style type="text/css">
        th .layui-table-cell {
            height: auto;
            line-height: 20px;
            padding: 0 5px;
            position: relative;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: normal;
            box-sizing: border-box;
        }
    </style>
}
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
    <legend>工程材料登记表</legend>
</fieldset>
<div>
    <form class="layui-form" id="FormInfo">
        <div class="layui-form-item">
            <label class="layui-form-label">主项目选择</label>
            <div class="layui-input-block">
                <select name="ProjectId" lay-verify="required" lay-search lay-filter="ProjectIdSelFilter">
                    <option value=""></option>
                    @for (int i = 0; i < ViewBag.ProjectList.Count; i++)
                    {
                        <option value="@ViewBag.ProjectList[i]["ProjectId"]">@ViewBag.ProjectList[i]["Name"]|@ViewBag.ProjectList[i]["ProjectCode"]|@ViewBag.ProjectList[i]["Type"]</option>
                    }
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">搜索</label>
            <div class="layui-input-block">
                <input type="text" id="SearchText" name="Title1" required lay-verify="required" onkeypress="getKey()" placeholder="材料名称" class="layui-input" style="width:300px;float:left;">
                <input type="text" value="" style="display:none" />
                <button type="button" class="layui-btn layui-btn-normal" style="float:left;" onclick="SearchFunc()"><i class="layui-icon">&#xe615;</i></button>
                <div class="layui-form-mid layui-word-aux">高级搜索</div>
                <button type="button" class="layui-btn layui-btn-danger" style="float:left;" id="BtnAdd"><i class="layui-icon">&#xe61f;</i>新增</button>
                <button type="button" class="layui-btn layui-btn-danger" id="UpLoadExcel">
                    <i class="layui-icon">&#xe67c;</i>上传文件(039表格)
                </button>

            </div>
        </div>

    </form>
    <table id="demo" lay-filter="MaterialTableList"></table>
</div>


<script type="text/template" id="LayerProgBar">
    <div class="layui-progress layui-progress-big" lay-showPercent="true" lay-filter="progressBar">
        <div class="layui-progress-bar layui-bg-blue" lay-percent="0%"></div>
    </div>

</script>

<script type="text/ng-template" id="LayerRefuFrom">
    <div>
        <form class="layui-form" id="RefuFrom" style="margin-top:10px;">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width:200px;">物料编码：<span id="spanRefuFromCode"></span></label>
                <label class="layui-form-label" style="width:400px;">规格名称：<span id="spanRefuFromSpecification"></span></label>

            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" style="width:170px;">ERP实际收货数量：<span id="RefuFromReceAmount" style="margin-right:30px;"></span></label>
                    <label class="layui-form-label" style="width:170px;">分包单位领用量：<span id="RefuFromSubTakeAmount" style="margin-right:30px;"></span></label>
                    <label class="layui-form-label" style="width:170px;">现场实际用量：<span id="RefuFromSubUseAmount" style="margin-right:30px;"></span></label>
                    <label class="layui-form-label" style="width:170px;">应退量：<span id="RefuFromRebackAmount" style="margin-right:30px;"></span></label>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" style="width:60px;">退料时间</label>
                    <div class="layui-input-inline" style="width:100px;">
                        <input type="text" name="SubRefuDate" value="" id="RefuFromSubRefuDate" placeholder="请输选择时间" lay-verify="required" required autocomplete="off" class="layui-input" >
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" style="width:100px;">退回公司数量</label>
                    <div class="layui-input-inline" style="width:80px;">
                        <input type="number" name="RemaAmount" id="RefuFromRemaAmount" value="" class="layui-input" lay-verify="required" required>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" style="width:100px;">退回地址</label>
                    <div class="layui-input-inline" style="width:150px;">
                        <select name="InvenAddressId" lay-verify="required" required>
                            <option value=""></option>
                            <option value="1">-3F库房</option>
                            <option value="2">游泳池库房</option>
                        </select>
                    </div>
                    <button type="button" class="layui-btn" id="LayerRefuBtnSave">保存</button>
                </div>
                @*<input type="text" name="Code" value="" id="RefuFromCode" style="display:none" />
                <input type="text" name="Specification" value="" id="RefuFromSpecification" style="display:none" />
                <input type="text" name="Unit" value="" id="RefuFromUnit" style="display:none" />*@
                <input type="text" name="InventoryId" value="" id="RefuFromInventoryId" style="display:none" />

                <button type="submit" id="LayerRefuFromSubmit" class="layui-btn" lay-submit lay-filter="LayerRefuFromVerify" style="display:none;">立即提交</button>
            </div>
            
        </form>
    </div>

</script>
<script>

    var ProjectId = ""
    var table;
    //注意：选项卡 依赖 element 模块，否则无法进行功能性操作
    layui.use(['form', 'table', 'upload', 'layer', 'element','laydate'], function ()
    {
        var element = layui.element;
        var upload = layui.upload;
        table = layui.table;
        var tab = parent.tab;
        var layer = layui.layer;
        var form = layui.form;
        var laydate = layui.laydate;

        var IsValidate = 0;
        var LayerIndex;
        var LayerRefu;
        element.init();

        form.on('submit(formVerify)', function (data)
        {
            //layer.msg(JSON.stringify(data.field));
            IsValidate = 1;
            return false;
        });
        form.on('submit(LayerRefuFromVerify)', function (data)
        {
            //layer.msg(JSON.stringify(data.field));
            IsValidate = 1;
            return false;
        });

        //这里是动态绑定的
        $("body").on("click",'#LayerRefuBtnSave', function ()
        {
            $("#LayerRefuFromSubmit").click();
            if (IsValidate == 1) {
                IsValidate = 0;
                var obj = $("#RefuFrom").serializeArray();
                var data = {};
                $.each(obj, function (i, v)
                {
                    data[v.name] = v.value;
                });
                
                //alert(JSON.stringify(data));
                //更新退货库存
                $.ajax({
                    type: "POST",
                    url: "/Inventory/RefuUpdate",
                    async: false,
                    contentType: "application/json",
                    dataType: "json",
                    data: JSON.stringify(data),
                    success: function (msg)
                    {
                        if (msg.result == "OK") {
                            table.reload("demo");
                            layer.close(LayerRefu);
                            //parent.layui.admin.events.closeThisTabs();
                        } else {
                            alert(msg.result);
                        }
                    }
                });
                //alert(JSON.stringify(data));
            }
        });

        $("#BtnAdd").on("click", function ()
        {
            if (ProjectId == "") {
                layer.msg('请选择主项目"', { icon: 6, time: 1000 });
                return;
            }
            index = layer.open({
                type: 2,
                title: ['新增库存条目', 'font-size:18px;'],
                area: ['900px', '600px'],
                content: '/Inventory/InveAddView?ProjectId=' + ProjectId  //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
            });
        });

        form.on('select(ProjectIdSelFilter)', function (data)
        {
            //console.log(data.elem); //得到select原始DOM对象
            //console.log(data.value); //得到被选中的值
            //console.log(data.othis); //得到美化后的DOM对象
            ProjectId = data.value;
            if (data.value == "") {
                table.reload("demo", {
                    where: {
                        SortName: "InventoryId", Order: "Desc", Condition: " and IsDelete<>1 and 1=0"
                    }
                });
            }
            else {
                table.reload("demo", {
                    where: {
                        SortName: "InventoryId", Order: "Desc", Condition: " and IsDelete<>1 and ProjectId=" + data.value
                    }
                });
            }
        });


        table.render({
            elem: '#demo'
            , method: 'post'
            //, height: 315
            , url: '/Inventory/InveTableRequest' //数据接口
            , page: true //开启分页
            , where: { SortName: "InventoryId", Order: "asc", Condition: " and IsDelete<>1 and 1=0" }
            , limit: 12
            , limits: [12, 50, 100]
            , cols: [[ //表头
                { field: 'Code', title: '物料编码', width: 110 }
                , { field: 'Specification', title: '规格名称', width: 250 }
                , { field: 'Unit', title: '单位', width: 70 }
                , { field: 'RequAmount', title: 'ERP提报数量', width: 75 }
                , { field: 'ReceAmount', title: '实际收货数量', width: 75 }
                , { field: 'ReceDate', title: '收货日期', width: 120 }
                , { field: 'SubTakeAmount', title: '分包单位领用量', width: 75 }
                , { field: 'SubRecedate', title: '领用时间', width: 120 }
                , { field: 'SubContact', title: '领用人', width: 75 }
                , {
                    title: "分包单位应退料量", width: 75,
                    templet: function (d)
                    {
                        return (d.SubTakeAmount - d.SubUseAmount).toFixed(3);
                    }
                }
                , { field: 'SubRefuDate', title: '退料时间', width: 120 }
                , { field: 'SubUseAmount', title: '现场实际用料', width: 75 }
                , { field: 'SettAmount', title: '结算书用料', width: 75 }
                , { field: 'RemaAmount', title: '退回公司数量', width: 75 }
                , {
                    field: 'InvenAddressId', title: '退回库房', width: 100,
                    templet: function (d)
                    {
                        if (d.InvenAddressId == "1") return "-3F库房";
                        if (d.InvenAddressId == "2") return "游泳池库房";
                        return "";
                    }
                }
                , { field: 'MaterialMemo', title: '备注', width: 200 }


                , {
                    title: "操作&nbsp<br>&nbsp", width: 200, fixed: 'right', align:'center',
                    templet: function (d)
                    {
                        return '<a class="layui-btn layui-btn-xs" lay-event="Refu">退料</a><a class="layui-btn layui-btn-xs" lay-event="Detail">编辑</a><a class="layui-btn layui-btn-xs" lay-event="TableDel">删除</a>';
                    }
                }
            ]]
        });

        table.on("tool(MaterialTableList)", function (obj)
        {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的DOM对象

            if (layEvent == 'Refu') {
                LayerRefu = layer.open({
                    type: 1,
                    title: ['退料到库存', 'font-size:18px;'],
                    area: ['900px', '400px'],
                    content: $("#LayerRefuFrom").html(),  //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                });
                form.render();
                $("#spanRefuFromCode").text(data.Code);
                $("#spanRefuFromSpecification").text(data.Specification);

                $("#RefuFromReceAmount").text(data.ReceAmount);
                $("#RefuFromSubTakeAmount").text(data.SubTakeAmount);
                $("#RefuFromSubUseAmount").text(data.SubUseAmount);
                $("#RefuFromRebackAmount").text((data.SubTakeAmount - data.SubUseAmount).toFixed(3));

                $("#RefuFromRemaAmount").val(data.RemaAmount);
                $("#RefuFromSubRefuDate").val(data.SubRefuDate);
                
                $("select[name=InvenAddressId]").find("option[value='" + data.InvenAddressId + "']").attr("selected", true);

                $("#RefuFromCode").val(data.Code);
                $("#RefuFromSpecification").val(data.Specification);
                $("#RefuFromUnit").val(data.Unit);
                $("#RefuFromInventoryId").val(data.InventoryId);



                form.render();
                laydate.render({
                    elem: '#RefuFromSubRefuDate' //指定元素
                });
                
            }


            if (layEvent == 'Detail') {
                layer.open({
                    type: 2,
                    title: ['新增库存条目', 'font-size:18px;'],
                    area: ['900px', '600px'],
                    content: '/Inventory/InveEditView?InventoryId=' + data.InventoryId  //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                });

            }


            if (layEvent == 'TableDel') {
                layer.confirm('<span class="layui-icon"></span>' + '是否真的要删除“物料编码：' + data.Code + '，规格名称:' + data.Specification + '”？', {
                    btn: ['确定删除', '取消'] //可以无限个按钮
                    , btn1: function (index)
                    {
                        //按钮【删除】的回调
                        //SSEditDelete
                        $.ajax({
                            type: "POST",
                            url: "/Inventory/InveDel" ,
                            async: false,
                            data: { "InventoryId": data.InventoryId, "OpTime": data.OpTime },
                            success: function (msg)
                            {
                                if (msg.result == "OK") {
                                    layer.msg('删除成功"', { icon: 6, time: 1000 });
                                    table.reload("demo", {
                                        //where: { SortName: "SSlistId", Order: "Desc", Condition: " and 1=1" }
                                    });
                                    //tab.close(tab.getId());
                                } else {
                                    alert("重置失败");
                                }
                            }
                        });
                        layer.close(index);
                    }
                    , btn2: function (index)
                    {
                        //按钮【按钮三】的回调
                        //alert("2");
                    }
                });
            }

        });

        var uploadInst = upload.render({
            elem: '#UpLoadExcel' //绑定元素
            , url: '/Inventory/Upload/' //上传接口
            , accept: 'file'
            , size: 1024000
            , exts: "xls|xlsx"
            , data: {
                "ProjectId": function ()
                {
                    return ProjectId;
                }
            }
            , before: function (obj)
            { //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                LayerIndex = layer.open({
                    type: 1,
                    title: '进度条',
                    area: ['700px', '200'],
                    content: $("#LayerProgBar").html(),
                    closeBtn: 0

                });
                //然后需要重新渲染一下上传进度条
                element.init();
            }
            , progress: function (e, percent)
            {
                console.log("进度：" + percent + '%');
                element.progress('progressBar', percent + '%');
            }
            , done: function (msg, index, upload)
            {
                //上传完毕回调
                layer.close(LayerIndex);
                if (msg.result != "OK") {
                    layer.msg(msg.result, { icon: 6, time: 10000 });
                }
                else {
                    layer.msg('上传成功', { icon: 6, time: 2000 });
                    table.reload("demo", {
                        //where: { SortName: "SSlistId", Order: "Desc", Condition: " and 1=1" }
                    });
                }

            }
            , error: function ()
            {
                //请求异常回调
                alert(msg.result);
            }
        });


    });

    //回车键
    function getKey()
    {
        if (event.keyCode == 13) {
            SearchFunc();
        }
    }

    function SearchFunc()
    {
        if (ProjectId == "") {
            layer.msg('请选择主项目"', { icon: 6, time: 1000 });
            return;
        }
        var text = $("#SearchText").val();
        if (text == "") {
            table.reload("demo", {
                where: {
                    SortName: "InventoryId", Order: "asc", Condition: " and IsDelete<>1 and ProjectId=" + ProjectId
                },
                page: {
                    curr: 1
                }
            });
        }
        else {
            table.reload("demo", {
                where: {
                    SortName: "InventoryId", Order: "asc", Condition: " and IsDelete<>1 and Specification like '%" + text + "%' and ProjectId=" + ProjectId
                },
                page: {
                    curr: 1
                }
            });
        }
    }
</script>


